#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 打印信息
info() {
    echo -e "${GREEN}[信息]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[警告]${NC} $1"
}

error() {
    echo -e "${RED}[错误]${NC} $1"
    exit 1
}

# 移除程序
remove_binary() {
    info "移除程序..."

    if [[ -f /usr/local/bin/deployer ]]; then
        sudo rm -f /usr/local/bin/deployer || error "移除程序失败"
    else
        warn "程序文件不存在"
    fi

    info "程序移除完成"
}

# 清理配置
clean_config() {
    info "清理配置..."

    # 清理配置目录
    if [[ -d ~/.deployer ]]; then
        rm -rf ~/.deployer || warn "清理配置目录失败"
    fi

    # 清理Shell配置
    SHELL_RC=""
    if [[ -f ~/.zshrc ]]; then
        SHELL_RC=~/.zshrc
    elif [[ -f ~/.bashrc ]]; then
        SHELL_RC=~/.bashrc
    fi

    if [[ -f "${SHELL_RC}" ]]; then
        # 移除环境变量配置
        sed -i.bak '/# Deployer Configuration/d' "${SHELL_RC}"
        sed -i.bak '/export PATH="\/usr\/local\/bin:\$PATH"/d' "${SHELL_RC}"
        sed -i.bak '/export DEPLOYER_HOME="\$HOME\/.deployer"/d' "${SHELL_RC}"
        rm -f "${SHELL_RC}.bak"
    fi

    info "配置清理完成"
}

# 清理缓存
clean_cache() {
    info "清理缓存..."

    # 清理Docker镜像
    if command -v docker &> /dev/null; then
        # 查找并删除相关的Docker镜像
        IMAGES=$(docker images --filter "reference=*deployer*" --format "{{.ID}}")
        if [[ -n "${IMAGES}" ]]; then
            echo "${IMAGES}" | xargs docker rmi -f || warn "清理Docker镜像失败"
        fi
    fi

    # 清理构建缓存
    rm -rf ~/.m2/repository/com/xindl/deployer 2>/dev/null
    rm -rf ~/.gradle/caches/modules-*/files-*/com.xindl.deployer 2>/dev/null

    info "缓存清理完成"
}

# 主函数
main() {
    echo "Deployer 卸载程序"
    echo "================="

    # 执行卸载步骤
    remove_binary
    clean_config
    clean_cache

    echo "================="
    info "卸载完成！"
    info "请执行 'source ${SHELL_RC}' 使配置生效"
}

# 执行主函数
main
